import Header from '@/components/Header.jsx'
import Footer from '@/components/Footer.jsx'
import Goods from '@/components/Goods.jsx'
import Counter from '@/components/Counter.jsx'

import styled from 'styled-components'
import { useState, useEffect } from 'react'
import { getCartAPI } from '@/api/cart.js'

const Wrapper = styled.div`
  padding: 40px 0 50px 0;
  font-size: 12px;
`

function App() {
  // 列表数据
  const [list, setList] = useState([])

  useEffect(() => {
    // 获取购物车列表数据的方法
    const initCartList = async () => {
      const { data: res } = await getCartAPI()
      setList(res.list)
    }
    initCartList()
  }, [])

  // 全选
  const [fullState, setFullState] = useState(false)

  useEffect(() => {
    const boo = list.every(item => item.goods_state)
    setFullState(boo)
  }, [list])

  // 总价
  const [amt, setAmt] = useState(0)
  useEffect(() => {
    const t = list.filter(x => x.goods_state).reduce((t, item) => (t += item.goods_price * item.goods_count), 0)
    setAmt(t)
  }, [list])

  // 总数量
  const [total, setTotal] = useState(0)
  useEffect(() => {
    const t = list.filter(x => x.goods_state).reduce((t, item) => (t += item.goods_count), 0)
    setTotal(t)
  }, [list])

  // 更新商品的勾选状态
  const updateGoodsState = e => {
    setList(
      list.map(item => {
        if (item.id === e.id) {
          return {
            ...item,
            goods_state: e.value
          }
        }
        return item
      })
    )
  }

  // 更新所有商品的勾选状态
  const updateAllState = boo => {
    setList(
      list.map(item => {
        return {
          ...item,
          goods_state: boo
        }
      })
    )
  }

  // 更新指定商品的数量
  const updateGoodsCount = (id, num) => {
    setList(
      list.map(item => {
        if (item.id === id) {
          return {
            ...item,
            goods_count: num
          }
        }
        return item
      })
    )
  }

  return (
    <Wrapper>
      <Header>购物车案例</Header>

      {list.map(item => {
        return (
          <Goods {...item} key={item.id} stateChange={updateGoodsState}>
            <Counter num={item.goods_count} onNumChange={num => updateGoodsCount(item.id, num)} />
          </Goods>
        )
      })}

      <Footer isFull={fullState} onFullChange={updateAllState} amount={amt.toFixed(2)} total={total} />
    </Wrapper>
  )
}

export default App
